const MYSQL = require("../../sql/mysql");
// 动态表
const DynamicSqlNaem = "article";
// 动态点赞记录表
const DynamicLogSqlName = "article_log";
/**
 * 获取动态运维数据
 * @return {promise<{code:string,msg:string}>}
 */
async function GetDynamicObserver() {
  try {} catch (error) { }
}

/**
 * 收藏动态
 * @return {promise<{code:string,msg:string}>}
 */
async function CollectDynamic(Request) { }
/**
 * 动态列表
 * @return {promise<{code:string,msg:string}>}
 */
async function GetDynamicList(Request) {
  try {
    let user = Request.$user;
    let query = Request.query;
    let {
      page = 1, // 当前页
      limit = 10, // 每页记录数量
    } = query;

    limit = limit < 1 ? (limit = 1) : limit;
    page = page < 1 ? (page = 1) : page;
    const conn = await MYSQL.promise().getConnection();
    // 获取列表数据
    let [list] = await conn.query(`
      SELECT 
      article.*,
			USER.id AS user_id,
			USER.avatar AS user_avatar,
			USER.nickname AS user_nickname,
			USER.username AS user_username,
      USER.introduce AS user_introduce,
			USER.gender AS user_gender,
			USER.state AS user_state
      FROM ${DynamicSqlNaem} 
      left join ${userSqlName} USER on article.user = USER.id
			LIMIT ${(page - 1) * limit + "," + page * limit}
		`);
    list = await Promise.all(
      list.map(async (item) => {
        // 动态创建时间
        let { id, create_time } = item;

        // 用dayjs加一个距离至今的时间
        item.ago_time = DayJs(create_time).from();

        item.authorId = item.user;

        // 当前用户是否为该动态作品
        item.if_my_dynamic = item.user == user;

        item.userInfo = {
          id: item.user_id,
          avatar: item.user_avatar,
          gender: item.user_gender,
          introduce: item.user_introduce,
          nickname: item.user_nickname,
          username: item.user_username,
          state: item.user_state,
        };

        let CommentListRedisPath = `${ProjectName}:Dynamic:Data:${item.id}:Comment:List`;

        let FoverListRedisPath = `${ProjectName}:Dynamic:Data:${item.id}:Fover:List`;

        let LockListRedisPath = `${ProjectName}:Dynamic:Data:${item.id}:Lock:List`;

        let CollectListRedisPath = `${ProjectName}:Dynamic:Data:${item.id}:Collect:List`;

        let Redis_Lock_Number = await Redis.zcard(LockListRedisPath);

        let Redis_Forver_Number = await Redis.zcard(FoverListRedisPath);

        let Redis_Collect_Number = await Redis.zcard(CollectListRedisPath);

        let Redis_Comment_Number = await Redis.zcard(CommentListRedisPath);

        // 动态点赞成员
        let fover_user_list = [];

        // 点赞成员数
        let forver_max_number = 9;

        // 获取动态点赞成员

        let Redis_Fover_user_list = await Redis.zrange(
          FoverListRedisPath,
          0,
          forver_max_number - 1
        );

        // 动态点赞成员列表
        fover_user_list = await Promise.all(
          Redis_Fover_user_list.map(async (id) => {
            let userAvatarRedisPath = `${ProjectName}:user:${id}:Info:Base`;
            let FoverUserInfo = await Redis.hgetall(userAvatarRedisPath);
            let { avatar, username, nickname, gender, state } = FoverUserInfo;
            return {
              avatar,
              id,
              username,
              nickname,
              gender,
              state,
            };
          })
        );
        // 查询Redis中用户是否点赞
        let user_Fover_Date = await Redis.zscore(FoverListRedisPath, user);
        if (user_Fover_Date) {
          // 用户点赞状态
          item.current_user_fover = true;
          // 用户点赞时间
          item.current_user_fover_date = user_Fover_Date;
        } else {
          // 用户点赞状态
          item.current_user_fover = false;
          // 用户点赞时间
          item.current_user_fover_date = null;
        }
        // 查询Redis中用户是否收藏
        let user_Collect_Date = await Redis.zscore(FoverListRedisPath, user);
        if (user_Collect_Date) {
          // 用户点赞状态
          item.current_user_collect = true;
          // 用户点赞时间
          item.current_user_collect_date = user_Collect_Date;
        } else {
          // 用户点赞状态
          item.current_user_collect = false;
          // 用户点赞时间
          item.current_user_collect_date = null;
        }
        // 评论数
        item.comment = Redis_Comment_Number;
        // 收藏数
        item.collect = Redis_Collect_Number;
        // 观看次数
        item.lock = Redis_Lock_Number;
        // 点赞数
        item.fover = Redis_Forver_Number;
        // 点赞成员列表
        item.fover_user_list = fover_user_list;

        item.imagesList = [
          item.image_1,
          item.image_2,
          item.image_3,
          item.image_4,
          item.image_5,
          item.image_6,
          item.image_7,
          item.image_8,
          item.image_9,
        ].filter((i) => i);

        // 缓存到Redis
        await Redis.hset(`${ProjectName}:Dynamic:Data:${id}:Info`, item);

        await Redis.zadd(`${ProjectName}:Dynamic:List`, [create_time, id]);

        delete item.user_fover_status;
        delete item.user_fover_date;
        delete item.user_id;
        delete item.user_avatar;
        delete item.user_nickname;
        delete item.user_introduce;
        delete item.user_username;
        delete item.user_gender;
        delete item.user_state;
        delete item.image_1;
        delete item.image_2;
        delete item.image_3;
        delete item.image_4;
        delete item.image_5;
        delete item.image_6;
        delete item.image_7;
        delete item.image_8;
        delete item.image_9;
        delete item.images;
        return item;
      })
    );
    // 获取数据总数 =====
    let totalResult = await conn.query(
      `
      SELECT Count(*) AS total FROM ${DynamicSqlNaem}
      `
    );
    let total = totalResult[0][0].total;
    let pages = Math.ceil(total / limit);
    await conn.release();
    return {
      code: 0,
      msg: "获取成功",
      data: {
        pages,
        list,
        page: Number(page),
        limit: Number(limit),
        total: Number(total),
      },
    };
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 获取动态信息
 * @return {promise<{code:string,msg:string}>}
 */
async function DynamicInfo(Request) {
  try {
    let user = Request.$user;
    let Query = Request.query;
    let { id } = Query;
    if (!id) {
      throw {
        code: 500,
        msg: "id不能为空",
      };
    }
    let data = await Redis.hgetall(`${ProjectName}:Dynamic:Data:${id}:Info`);
    // 判断data是否为空对象
    if (Object.keys(data).length === 0) {
      // 获取MYSQL实例
      const conn = await MYSQL.promise().getConnection();
      let SqlName = "article";
      // 查询数据
      let sql = `SELECT * FROM ${SqlName} WHERE id = ${id}`;
      let [res] = await conn.query(sql);
      data = res;
      await Redis.hset(`${ProjectName}:Dynamic:Data:${id}:Info`, res);
      // 释放连接
      await conn.release();
    }
    let { state } = data;
    if (state == 1) {
      return {
        code: 0,
        msg: "操作成功",
        data,
      };
    } else {
      throw {
        code: 500,
        msg: "动态不存在",
      };
    }
  } catch (error) {
    console.log(error);
    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 发布动态
 * @return {promise<{code:string,msg:string}>}
 */
async function PublishDynamic(Request, user) {
  try {
    let from = Request.body;
    // 用户名
    let user = Request.$user;
    let {
      type, // 文章类型
      title, // 文章标题
      value, // 文章内容
      disclosure, // 是否公开
      images = [], // 图集
      video = null, // 视频
      topic = [], // 话题
    } = from;
    // 获取MYSQL实例
    const Conline = await MYSQL.promise().getConnection();
    // 插入数据
    await Conline.query(
      `
            INSERT INTO ${DynamicSqlNaem} 
            (user,type,title,value) 
            VALUES (${user},${type},${title},${value})
            `,
      [user, type, title, value]
    );
    // 回收池
    await Conline.release();
    return {
      code: 0,
      msg: "发布成功",
    };
  } catch (error) {
    let { msg } = error;
    if (msg) {
      throw error;
    } else {
      throw { code: 500, msg: "操作失败" };
    }
  }
}
/**
 * 评论动态
 * @return {promise<{code:string,msg:string}>}
 */
async function CommentDynamic(Request) {
  try {
    let user = Request.$user;
    let Body = Request.body;
    let {
      id,
      value, // 评论的文本内容
      image, // 评论的图片
      dynamic_id, // 帖子id
      dynamic_user, // 帖子发布的用户
      comment_top_id,
      reply_comment, // 回复的评论id
      reply_user,
    } = Body;
    if (!dynamic_id) {
      throw {
        code: 500,
        msg: "动态ID不能为空",
      };
    }
    let type = reply_user && reply_comment ? 1 : 0;
    // 当前时间时间戳
    let NowDate = Request.$requestTime;
    let inset = {
      id,
      type, // 评论类型   0:一级评论  1:多级评论
      user, // 发表评论的用户id
      image, // 评论图片
      value, // 评论的文本内容
      fover: 0,
      comment_top_id,
      dynamic_id, // 帖子id
      dynamic_user, // 帖子发布的用户
      reply_comment, // 回复的评论id
      reply_user, // 回复的用户id
      created_time: NowDate, // 评论时间
      state: 1,
    };
    if (type == 0) {
      let RedisInfoPath = `${ProjectName}:Dynamic:Data:${dynamic_id}:Comment:Data:${id}:Info`;
      let RedisListPath = `${ProjectName}:Dynamic:${dynamic_id}:Comment:List`;
      await Redis.hset(RedisInfoPath, inset);
      await Redis.zadd(RedisListPath, [NowDate, id]);
    } else if (type == 1) {
      await Redis.hset(
        `${ProjectName}:Dynamic:${dynamic_id}:CommentInfo:${id}:Reply:${id}`,
        inset
      );
      // await Redis.hset(`${ProjectName}:Dynamic:${dynamic_id}:comment`,inset)
    }
    return {
      code: 0,
      msg: "操作成功",
    };
  } catch (error) {
    throw {
      code: 500,
      msg: "评论失败",
    };
  }
}
/**
 * 回复评论
 * @return {promise<{code:string,msg:string}>}
 */
async function ReplyComment(Request) { }
/**
 * 点赞评论
 * @return {promise<{code:string,msg:string}>}
 */
async function FoverComment(Request) { }
/**
 * 动态评论列表
 * @return {promise<{code:string,msg:string}>}
 */
async function CommentList(Request) {
  try {
    let Query = Request.query;
    let {
      id,
      page = 1, // 当前页
      limit = 10, // 每页记录数量
    } = Query;
    let user = Request.$user;
    limit = limit < 1 ? (limit = 10) : limit;
    page = page < 1 ? (page = 1) : page;
    let SqlName = "article_comment";
    // 获取MYSQL实例
    const conn = await MYSQL.promise().getConnection();
    // Mysql 自增
    let [list] = await conn.query(`
      SELECT 
      article_comment.*,
      article_comment.id AS CommentId,
			USER.id AS user_id,
			USER.avatar AS user_avatar,
			USER.nickname AS user_nickname,
			USER.username AS user_username,
      USER.introduce AS user_introduce,
			USER.gender AS user_gender,
			USER.state AS user_state,
      (
        SELECT COUNT(*) 
        FROM article_comment 
        WHERE 
        article_comment.reply_comment = CommentId
      ) AS Reply_Count
      FROM ${SqlName}
      left join ${userSqlName} USER on article_comment.user = USER.id
      WHERE article_comment.dynamic_id = ${id} AND article_comment.type = 0
      LIMIT ${(page - 1) * limit + "," + page * limit}
    `);
    list = await Promise.all(
      list.map(async (item) => {
        // 动态创建时间
        let { create_time } = item;
        // 用dayjs加一个距离至今的时间
        // item.ago_time = DayJs(create_time).from();
        item.ago_time = "昨天21:35";
        item.if_author = item.user == id;
        item.if_my_comment = item.user == user;
        item.userInfo = {
          id: item.user_id,
          avatar: item.user_avatar,
          gender: item.user_gender,
          introduce: item.user_introduce,
          nickname: item.user_nickname,
          username: item.user_username,
          state: item.user_state,
        };
        // 点赞
        item.fover = {
          current_user: {
            fover: false,
            status: false,
            date: null,
          },
          number: 0,
        };
        let Reply_Count = item.Reply_Count;
        let Reply_limit = 5;
        let Reply_Pages = Math.ceil(Reply_Count / Reply_limit);
        item.Reply = {
          page: 0,
          pages: Reply_Pages,
          limit: Reply_limit,
          total: Reply_Count,
          list: [],
        };
        item.ip_address = "山东";
        await Redis.hset(
          `${ProjectName}:Dynamic:Data:${id}:Comment:Data:${item.id}:Info`,
          item
        );
        await Redis.zadd(`${ProjectName}:Dynamic:Data:${id}:Comment:List`, [
          item.created_time,
          item.id,
        ]);
        delete item.user;
        delete item.user_id;
        delete item.user_avatar;
        delete item.user_nickname;
        delete item.user_introduce;
        delete item.user_username;
        delete item.user_gender;
        delete item.user_state;
        delete item.CommentId;
        delete item.examine_user;
        delete item.examine_time;
        return item;
      })
    );
    // 释放连接
    await conn.release();
    return {
      code: 0,
      msg: "操作成功",
      data: {
        page,
        pages: null,
        limit,
        list,
      },
    };
  } catch (error) {
    console.log(error);

    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 动态评论回复列表
 * @return {promise<{code:string,msg:string}>}
 */
async function CommentReplyList(Request) {
  try {
    let Query = Request.query;

    let { id, page, limit, dynamic_id } = Query;
    limit = limit < 1 ? (limit = 10) : limit;
    page = page < 1 ? (page = 1) : page;
    let SqlName = "article_comment";
    // 获取MYSQL实例
    const conn = await MYSQL.promise().getConnection();

    let [list] = await conn.query(`
      SELECT 
      ${SqlName}.*,
      USER.id AS user_id,
			USER.avatar AS user_avatar,
			USER.nickname AS user_nickname,
			USER.username AS user_username,
      USER.introduce AS user_introduce,
			USER.gender AS user_gender,
			USER.state AS user_state
      
      FROM ${SqlName}
      left join ${userSqlName} USER on ${SqlName}.user = USER.id
      WHERE 
      ${SqlName}.type = 1 AND 
      ${SqlName}.dynamic_id = ${dynamic_id} AND 
      ${SqlName}.reply_comment = '${id}' AND
      ${SqlName}.state = 1
      LIMIT ${(page - 1) * limit + "," + page * limit}
    `);

    list = await Promise.all(
      list.map(async (item) => {
        // 动态创建时间
        let { create_time } = item;
        // 用dayjs加一个距离至今的时间
        // item.ago_time = DayJs(create_time).from();
        item.ago_time = "昨天21:35";
        item.userInfo = {
          id: item.user_id,
          avatar: item.user_avatar,
          gender: item.user_gender,
          introduce: item.user_introduce,
          nickname: item.user_nickname,
          username: item.user_username,
          state: item.user_state,
        };
        item.ip_address = "山东";
        delete item.user;
        delete item.user_id;
        delete item.user_avatar;
        delete item.user_nickname;
        delete item.user_introduce;
        delete item.user_username;
        delete item.user_gender;
        delete item.user_state;
        delete item.CommentId;
        delete item.examine_user;
        delete item.examine_time;

        return item;
      })
    );
    // 释放连接
    await conn.release();

    return {
      code: 0,
      msg: "操作成功",
      data: {
        page,
        pages: null,
        limit,
        list,
      },
    };
  } catch (error) {
    console.log(error);

    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 删除动态
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteDynamic(Request, user) {
  try {
    let user = Request.$user;
    let body = Request.body;
    let { id } = body;
    // 获取MYSQL实例
    const Conline = await MYSQL.promise().getConnection();
    // 执行删除
    await Conline.query(
      `
       DELETE FROM ${DynamicSqlNaem} WHERE id = ${id} and user = ${user}
     `
    );
    // 回收池
    await Conline.release();
    return {
      code: 0,
      msg: "删除成功",
    };
  } catch (error) {
    throw {
      code: 500,
      msg: "删除失败",
    };
  }
}
/**
 * 编辑动态
 * @return {promise<{code:string,msg:string}>}
 */
async function updateDynamic(Request, user) {
  try {
    let { user, id } = params;
  } catch (error) {
    throw {
      code: 500,
      msg: "修改失败",
    };
  }
}
/*
 * 点赞动态 (点赞与取消都在)
 * @return {promise<{code:string,msg:string}>}
 */
async function FoverDynamic(Request, user) {
  try {
    let user = Request.$user;
    let Body = Request.body;
    let { id = 1, fover } = Body;
    // 当前时间时间戳
    let date_now = "1";
    // 获取MYSQL实例
    const Conline = await MYSQL.promise().getConnection();
    // 开启Mysql事务
    await Conline.beginTransaction();
    try {
      // 查询是否有点赞记录
      let fover_result = await Conline.query(`
				SELECT * FROM ${DynamicLogSqlName} WHERE user = '${user}' && article = '${id}'
			`);
      // 如果有记录
      if (fover_result[0].length > 0) {
        // 删除点赞记录
        await Conline.query(`
					DELETE FROM ${DynamicLogSqlName} WHERE user = '${user}' && article = '${id}'
				`);
        // Mysql 自减
        await Conline.query(
          `UPDATE ${DynamicSqlNaem} SET fover = fover - 1 WHERE id = ? && user = ?`,
          [id, user]
        );
        // 提交事务
        await Conline.commit();

        // 回收池
        await Conline.release();

        // 返回结果
        return {
          code: 0,
          msg: "取消点赞成功",
        };
      } else {
        // 添加点赞记录到MYSQL
        let inset = {
          article: id,
          user,
          created_time: date_now,
        };
        await Conline.query(`insert into ${DynamicLogSqlName} SET ? `, inset);
        // Mysql 自增
        await Conline.query(
          `UPDATE ${DynamicSqlNaem} SET fover = fover + 1 WHERE id = ? && user = ?`,
          [id, user]
        );
        // 提交事务
        await Conline.commit();
        // 回收池
        await Conline.release();
        // 返回结果
        return {
          code: 0,
          msg: "点赞成功",
        };
      }
    } catch (error) {
      // 撤回事务
      await Conline.rollback();
      // 回收池
      await Conline.release();
      throw {
        code: 500,
        msg: "点赞失败",
      };
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 动态点赞列表
 * @return {promise<{code:string,msg:string}>}
 */
async function FoverList(Request) {
  try {
    let Query = Request.query;
    let { id, page, limit } = Query;
    limit = limit || 10;
    page = page || 1;
    let FoverListRedisPath = `${ProjectName}:Dynamic:Data:${id}:Fover:List`;
    let Redis_Forver_Number = await Redis.zcard(FoverListRedisPath);
    // 根据页码和limit计算偏移量
    let list = await Redis.zrevrange(
      FoverListRedisPath,
      (page - 1) * limit,
      page * limit - 1
    );
    // 计算总页数
    let pages = Math.ceil(Redis_Forver_Number / limit);
    return {
      code: 0,
      msg: "操作成功",
      data: {
        id,
        page,
        pages,
        number: Redis_Forver_Number,
        list: list,
        total: Redis_Forver_Number,
      },
    };
  } catch (error) {
    console.log(error);
    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
module.exports = {
  CommentList,
  CommentReplyList,
  FoverList,
  GetDynamicObserver,
  CommentDynamic,
  ReplyComment,
  FoverComment,
  GetChannelList,
  UpdateChannel,
  CreateChannel,
  DeleteChannel,
  PublishDynamic,
  DeleteDynamic,
  updateDynamic,
  FoverDynamic,
};
